<?php
declare (strict_types=1);

namespace app\command;

use app\common\model\Transfer;
use app\common\service\TransfersServer;
use think\console\Command;
use think\console\Input;
use think\console\Output;
use think\facade\Config;

/**
 * 批量转账定时器
 * Class BatchTransfers
 * @package app\command
 */
class BatchTransfers extends Command
{
    protected function configure()
    {
        // 指令配置
        $this->setName('batchtransfers')
            ->setDescription('the batchtransfers command');
    }

    protected function execute(Input $input, Output $output)
    {
        // 指令输出
        $output->writeln('批量转账开始');

        $payMethods = array_keys(Config::get('payment.transfersbatch'));

        if (empty($payMethods)) {
            $output->writeln('没有需要批量转账的支付方式');
            return;
        }

        // 查询是否存在待转账的申请（批量转账的）
        $payMethods = Transfer::where('transferStatus', 0)
            ->where('transferBatchId', 0)
            ->whereIn('payMethod', $payMethods)
            ->field(['payMethod'])
            ->group('payMethod')
            ->select()
            ->column('payMethod');

        if (empty($payMethods)) {
            $output->writeln('没有待批量转账记录');
            return;
        }

        // 调用批量转账服务，进行处理
        foreach ($payMethods as $payMethod) {
            $this->getTransfersServer()->batchTransfers($payMethod);
        }

        $output->writeln('批量转账结束');
    }

    private function getTransfersServer(): TransfersServer
    {
        return app(TransfersServer::class);
    }
}
